//
// Author: zxc
// Date: 2021/4/15
// Copyright (c) 2021 zxc All rights reserved.
//

#include <iostream>
using std::cout;
using std::endl;

extern "C"
{
#include "lauxlib.h"
#include "lualib.h"
#include "lua.h"
#include "lapi.h"
}

// 封装一个宏处理lua堆栈pop
#define PopLuaInt(L, val) \
{                               \
    val = int(lua_tonumber(L, lua_gettop(L))); \
    lua_pop(L, 1); \
}

#define PopLuaDouble(L, val) \
{\
    val = lua_tonumber(L, lua_gettop(L)); \
    lua_pop(L, 1); \
}

int Print(lua_State* L)
{
    switch (lua_type(L, 1))
    {
        case LUA_TNIL:
            cout << "nil" << endl;
            break;
        case LUA_TNUMBER:
            cout << lua_tonumber(L, 1) << endl;
            break;
        case LUA_TBOOLEAN:
            cout << (lua_toboolean(L, 1) ? "true" : "false") << endl;
            break;
        case LUA_TSTRING:
            cout << lua_tostring(L, 1) << endl;
            break;
        case LUA_TNONE:
            cout << "Invalid input" << endl;
            break;
    }

    return 0;
}

int GetSum(lua_State* L)
{
    if(!lua_isnumber(L, 1) || !lua_isnumber(L, 2))
    {
        luaL_error(L, "Invalid params");
    }
    else
    {
        auto result = lua_tonumber(L, 1) + lua_tonumber(L, 2);
        lua_pushnumber(L, result);
    }

    return 1;
}

int main()
{
    lua_State* L = luaL_newstate();

    lua_register(L, "print", Print);
    lua_register(L, "get_sum", GetSum);

    int errorCode = luaL_dofile(L, "scripts/test.lua");
    if(errorCode)
    {
        cout << "ErrorCode: " << errorCode << endl;
        return -1;
    }

//    int x = 0;
//    int y = 32;
//    double a = 0.;
//    double b = 90.;
//    cout << x << " " << y << " " << a << " " << b << " " << lua_gettop(L) << endl;
//    lua_pushnumber(L, y);
//    lua_pushnumber(L, b);
//    cout << x << " " << y << " " << a << " " << b << " " << lua_gettop(L) << endl;
//    PopLuaDouble(L, a);
//    cout << x << " " << y << " " << a << " " << b << " " << lua_gettop(L) << endl;
//    PopLuaInt(L, x);
//    cout << x << " " << y << " " << a << " " << b << " " << lua_gettop(L) << endl;
//    lua_close(L);



    return 0;
}

